<template>
  <div>
    <xr-header
      style="padding: 15px 28px"
      icon-class="wk wk-invoice"
      icon-color="#13BF97"
      label="销售表单上限设置"
    >
    </xr-header>
    <div class="crm-container">
      <flexbox class="tableHeader">
        <div class="flex">
          <div class="lable">姓名：</div>
          <el-input
            v-model="params.realname"
            placeholder="请输入查询姓名"
          ></el-input>
          <el-button @click="searchFn" type="primary" style="margin-left: 10px"
            >查询</el-button
          >
        </div>
        <div class="flex">
          <div class="lable">部门：</div>
          <xh-structure-cell-mul
            radio
            class="xh-structure-cell"
            @valueChange="structureChange"
            type="1"
          />
        </div>
      </flexbox>
      <el-table
        v-loading="loading"
        id="crm-table"
        :row-height="40"
        :data="list"
        :height="tableHeight"
        :cell-class-name="cellClassName"
        :header-cell-class-name="headerCellClassName"
        use-virtual
        class="n-table--border"
        stripe
        border
        highlight-current-row
        style="width: 100%"
        :style="scene.length > 0 ? 'margin-top:42px' : ''"
      >
        <el-table-column label="序号" type="index" width="50">
        </el-table-column>
        <el-table-column prop="realname" label="成员" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="num" label="表单上限数量" show-overflow-tooltip>
        </el-table-column>
        <el-table-column
          v-if="crm[crmType].setupLeadsNumber.save"
          :resizable="false"
          label="操作"
          fixed="right"
          width="150"
        >
          <template slot-scope="scope">
            <el-button type="primary" plain @click.native="editFn(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
        <el-table-column />
      </el-table>
      <div class="p-contianer">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size.sync="pageSize"
          :total="total"
          class="p-bar"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 相关详情页面 -->
    <c-r-m-all-detail
      :visible.sync="showDview"
      :crm-type="rowType"
      :id="rowID"
      class="d-view"
      @handle="handleHandle"
    />
    <el-dialog
      title="编辑"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="成员">
          <el-input v-model="form.realname" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="表单上限数量">
          <el-input v-model="form.num"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="handleClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { queryUserList, addOrupdate, queryByIdAPI } from "@/api/crm/set-module";
import CheckStatusMixin from "@/mixins/CheckStatusMixin";
import XrHeader from "@/components/XrHeader";
import XrTableHeader from "@/components/XrTableHeader";
import { mapGetters } from "vuex";
import CRMAllDetail from "@/views/crm/components/CRMAllDetail";
import WkEmpty from "@/components/WkEmpty";
import XhStructureCellMul from "@/components/CreateCom/XhStructureCellMul";

export default {
  name: "set-mudule",
  components: {
    XrHeader,
    XrTableHeader,
    CRMAllDetail,
    WkEmpty,
    XhStructureCellMul,
  },
  mixins: [CheckStatusMixin],
  props: {},
  data() {
    return {
      loading: false,
      crmType: "setup",
      dialogVisible: false,
      tableHeight: document.documentElement.clientHeight - 235, // 表的高度
      filterParams: {
        invoiceStatus: "",
        invoiceNumber: "",
        logisticsNumber: "",
        customerName: "",
        realInvoiceDate: "",
        checkStatus: "",
        ownerUserId: [],
      },
      filterCustomers: {
        customer: [],
        purposecustomer: [],
      },
      scene: "",
      scenes: [],
      showFilter: false, // 控制筛选框
      // filters: invoiceFilterFields,
      filterObj: { form: [] }, // 筛选确定数据
      list: [],
      fieldList: ["序号", "成员", "表单数量上限"], // invoice_status
      currentPage: 1,
      pageSize: 15,
      pageSizes: [15, 30, 60, 100],
      total: 0,
      selectionList: [], // 勾选数据 用于全局导出
      isCreate: false,
      rowDetail: {},
      markShow: false,
      isResetInvoice: false,
      transferDialogShow: false,
      showDview: false,
      rowType: "",
      rowID: "",
      params: {
        deptId: "",
        limit: 15,
        page: 0,
        realname: "",
      },
      form: {
        realname: "",
        num: "",
        id: "",
      },
    };
  },
  computed: {
    ...mapGetters(["crm", "userInfo"]),
    handles() {
      const temps = [];
      if (this.crm && this.crm[this.crmType]) {
        if (this.crm[this.crmType].delete) {
          temps.push({
            label: "删除",
            command: "delete",
            icon: "delete",
          });
        }

        if (
          this.crm[this.crmType].resetInvoiceStatus &&
          this.selectionList.length == 1
        ) {
          temps.push({
            label: "重置开票信息",
            command: "reset",
            icon: "reset",
          });
        }

        if (this.crm[this.crmType].transfer) {
          temps.push({
            label: "转移",
            command: "transfer",
            icon: "transfer",
          });
        }
      }
      return temps;
    },
    // 是否能操作
    canUpdateStatus() {
      return (
        this.crm &&
        this.crm[this.crmType] &&
        this.crm[this.crmType].resetInvoiceStatus
      );
    },
    // 是否能保存
    canSave() {
      return this.crm && this.crm[this.crmType] && this.crm[this.crmType].save;
    },
  },
  watch: {},
  created() {
    // 控制table的高度
    window.onresize = () => {
      this.updateTableHeight();
    };

    // this.debouncedRefreshList = debounce(500, () => {
    //   this.refreshList()
    // })
    this.refreshList();
  },

  beforeDestroy() {},
  mounted() {
    console.log(this.userInfo, "7777", this.params, this.crm[this.crmType]);
    // this.params.deptId = this.userInfo.deptId
    // this.getList()
  },
  methods: {
    handleClose() {
      this.dialogVisible = false;
    },
    /**
     * 刷新
     */
    refreshList() {
      this.handleCurrentChange(1);
    },
    editFn(item) {
      this.dialogVisible = true;
      this.form.realname = item.realname;
      this.form.num = item.num;
      this.form.id = item.userId;
    },
    onSubmit() {
      let params = {
        num: this.form.num,
        ownerUserId: this.form.id,
        setupUserId: this.userInfo.userId,
      };
      console.log(params);
      addOrupdate(params).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: "success",
            message: "保存成功",
          });
          this.dialogVisible = false;
          this.getList();
        }
      });
    },
    // /**
    //  * 更改每页展示数量
    //  */
    // handleSizeChange(val) {
    //   this.pageSize = val;
    //   this.getList();
    // },
    structureChange(data) {
      console.log(111, data);
      if (data.value) {
        this.scene = data.value;
      } else {
        this.scene = "";
      }
      this.getList();
    },

    /**
     * 更改当前页数
     */
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },
    searchFn() {
      this.currentPage = 1;
      this.getList();
    },
    /**
     * 获取列表
     */
    getList() {
      console.log(this.params, "参数");
      this.loading = true;
      const params = {
        page: this.currentPage,
        limit: 15,
        deptIdList: [],
        label: 0,
        pageType: 1,
        realname: "",
        roleId: null,
        status: 0,
        realname: this.params.realname,
      };
      if (this.scene.length>0) {
        params.deptIdList = this.scene;
        params.dataType = 7;
      }

      queryUserList(params)
        .then((res) => {
          console.log(res.data, "08766");
          this.list = res.data.list;
          this.total = res.data.totalRow;
          this.loading = false;
          this.$nextTick(() => {
            document.querySelector(".el-table__body-wrapper").scrollTop = 1;
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },

    // 0待审核、1审核中、2审核通过、3已拒绝 4已撤回 5未提交
    getStatusStyle(status) {
      return {
        backgroundColor: this.getStatusColor(status),
      };
    },

    /**
     * 改变负责人筛选条件
     */
    changeUserCell(data) {
      this.filterParams.ownerUserId = data.value;
      this.refreshList();
    },

    /**
     * 表头勾选
     */
    handleSelectionChange(val) {
      this.selectionList = val; // 勾选的行
    },

    /**
     * 列表操作
     */
    handleCommand(command) {
      if (command == "delete") {
        this.$confirm("确定要删除吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.loading = true;
            crmInvoiceDeleteIdsAPI(
              this.selectionList.map((item) => item.invoiceId)
            )
              .then((res) => {
                this.loading = false;
                this.$message({
                  type: "success",
                  message: "删除成功",
                });
                this.refreshList();
              })
              .catch(() => {
                this.loading = false;
              });
          })
          .catch(() => {});
      } else if (command == "transfer") {
        this.transferDialogShow = true;
      } else {
        this.rowDetail = this.selectionList[0];
        this.isResetInvoice = true;
        this.markShow = true;
      }
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === "invoiceApplyNumber") {
        return "can-visit--underline can-visit--bold";
      } else {
        return "";
      }
      //  else if (
      //   column.property === 'customerName' ||
      //   column.property === 'contractNum'
      // ) {
      //   return 'can-visit--underline'
      // }
    },

    headerCellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === "invoiceApplyNumber") {
        return "header-can-visit-backgroud";
      }
      return "";
    },

    /**
     * 详情操作
     */
    handleHandle(data) {
      if (
        [
          "alloc",
          "get",
          "transfer",
          "transform",
          "delete",
          "put_seas",
          "exit-team",
        ].includes(data.type)
      ) {
        this.showDview = false;
      }

      this.getList();
    },

    /**
     * 查看详情
     */
    handleRowClick(row, column, event) {
      if (column.property === "customerName") {
        this.rowID = row.customerId;
        this.rowType = "customer";
        this.showDview = true;
      } else if (column.property === "contractNum") {
        this.rowID = row.contractId;
        this.rowType = "contract";
        this.showDview = true;
      } else if (column.property === "invoiceApplyNumber") {
        this.rowID = row.invoiceId;
        this.rowType = "invoice";
        this.showDview = true;
      } else {
        this.showDview = false;
      }
    },

    /**
     * 创建点击
     */
    createClick() {
      this.isCreate = true;
    },

    /**
     * 切换场景
     */
    sceneChange() {
      this.refreshList();
    },

    showFilterClick() {
      this.showFilter = true;
    },

    handleFilter(form) {
      this.filterObj = form;
      this.showFilter = false;
      this.refreshList();
      this.updateTableHeight();
    },

    handleDeleteField(data) {
      this.filterObj = data.obj;
      this.refreshList();
      this.updateTableHeight();
    },

    /**
     * 更新表高
     */
    updateTableHeight() {
      var offsetHei = document.documentElement.clientHeight;
      var removeHeight = 0;

      if (
        this.filterObj &&
        this.filterObj.obj &&
        this.filterObj.obj.length > 0
      ) {
        removeHeight = 285;
      } else {
        removeHeight = 235;
      }
      this.tableHeight = offsetHei - removeHeight;
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/.structureMul > .block_reshow {
  left:-430px;
}
/deep/ .xr-table-header {
  border-bottom: 1px solid #e6e6e6;
  border-top: 1px solid #e6e6e6;

  .scene-select {
    width: 180px;
  }
}

.status-mark {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: $xr-border-radius-base;
}
.xh-structure-cell {
  width: 235px;
  margin-right: 15px;
}
.tableHeader {
  border-bottom: 1px solid #e6e6e6;
  border-top: 1px solid #e6e6e6;
  background-color: #ffffff;
  display: flex;
  flex-direction: row;
}
.flex {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 10px 20px;
}
.lable {
  width: 70px;
}
</style>
